package com.genius.mobile_page.siji.service.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.other.entity.FillAddJson;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.other.entity.SessionJson;
import com.genius.adminmanager.user.entity.UserJson;
import com.genius.dingding.util.GeniusConfig;
import com.genius.mobile_page.common.ErrorResponseData;
import com.genius.mobile_page.common.ResponseData;
import com.genius.mobile_page.common.SuccessResponseData;
import com.genius.mobile_page.pandian.pandianUtil;
import com.genius.mobile_page.pandian.service.PandianEveryService;
import com.genius.mobile_page.pandian.service.PandianService;
import com.genius.mobile_page.pingjia.PingjiaUtil;
import com.genius.mobile_page.pingjia.service.PingjiaServiceAdapter;
import com.genius.mobile_page.siji.service.SijiqiandaoService;
import com.genius.unite_platform.meeting_info.entity.Meeting_infoEntity;
import com.genius.unite_platform.meeting_info_detail.entity.Meeting_info_detailEntity;
import com.genius.unite_platform.notice_info.entity.Notice_infoEntity;
import com.genius.unite_platform.work_plan_info.entity.Work_plan_infoEntity;
import com.genius.workflow.element.SQLBean;
import com.genius.workflow.page.PageResult;
import com.genius.workflow.page.SearchResult;
import com.genius.workflow.page.SqlLang;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools;
import com.genius.workflow.util.DBTools2;
import com.genius.workflow.util.DBUtils;
import com.genius.workflow.util.GetNo;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;

@Service("sijiqiandaoService")
public class SijiqiandaoServiceImpl implements SijiqiandaoService{

	@Override
	public ResponseData getShopWeizhi(JSONObject parms) {
		StringBuilder sql = new StringBuilder("select s1.*,s2.deptname shopname"
//				+ ",s3.sEmployeeNO,s3.sEmployeeName,s3.sZoneMagNO,s3.sZoneMagName,s3.sDirectorNO,s3.sDirectorName"
				+ " from "
        		+ "(select shopcode,latitude,longitude,address,(abs(latitude-?)+abs(longitude-?)) cha"
        		+ " from "+GeniusConfig.XUNDIANDATABASE+".shop_jingwei_wuliu a where abs(latitude-?) <= 0.01 and abs(longitude-?) < 0.01) s1 "
        		+ " join "
        		+ "(select deptcode,deptname from "+GeniusConfig.CAIJIDATABASE+".dict_department where type =1) s2 "
				+ " on s1.shopcode =s2.deptcode "
//	            		+ " left join "
//	            		+GeniusConfig.XUNDIANDATABASE+".dict_tuserstorehistory s3 on s1.shopcode =s3.sStoreNO"
        		);
		try {
			JSONArray params = new JSONArray();
			params.add(parms.getString("latitude"));
			params.add(parms.getString("longitude"));
			params.add(parms.getString("latitude"));
			params.add(parms.getString("longitude"));

			
			sql.append(" ");
			if(ObjectUtil.isEmpty(parms.getString("nolimit"))){
				sql.append(" order by cha limit 5");
			}
			System.out.println(sql);
			JSONArray result = DBUtils.selectArr(sql.toString(),params.toArray());
			if(result != null && result.size() > 0){
				return new SuccessResponseData(result);
			}else{
				return new ErrorResponseData("附近没有门店信息");
			}
			
			
		} catch (SQLException throwables) {
			
			throwables.printStackTrace();
			return new ErrorResponseData("数据库操作失败！！");
		} catch (Exception e) {
			e.printStackTrace();
			return new ErrorResponseData(e.getMessage());
		}
	}

	@Override
	public ResponseData insertSiji_qiandao_every(JSONObject parms) {
		Connection conn = null;
		ResponseData response = null;
        try {
        	//打开连接
        	conn = DBUtils.getConnect();
        	String shopcode = "";
        	String sqlCunzai = "select shopcode from siji_qiandao_every"
					+ " where shopcode = '"+parms.getString("shopcode")+"' and qiandaoDate = CURDATE()";
			ResultSet cunzaiRs = DBUtils.query(conn, sqlCunzai);
			if(cunzaiRs.next()){
				shopcode = cunzaiRs.getString("shopcode");
			}
			cunzaiRs.close();
			//不存在信息
        	if(ObjectUtil.isEmpty(shopcode)){
        		DBUtils.beginTransaction(conn);
            	JSONObject dataJson = new JSONObject();
            	String sql ="insert into siji_qiandao_every (shopcode,shopname,qiandaoDate,shoplatitude,shoplongitude"
            			+ ",shopaddress,latitude,longitude,address,remark,flag,imgurl,lrr,lrsj) "
    					+ "values ('"+parms.getString("shopcode")+"','"+parms.getString("shopname")+"',now()"
    					+ ",'"+parms.getString("shoplatitude")+"','"+parms.getString("shoplongitude")+"'"
    					+ ",'" + parms.getString("shopaddress") + "','" + parms.getString("latitude") + "'"
    					+ ",'"+parms.getString("longitude")+"','"+parms.getString("address")+"'"
    					+ ",'"+parms.getString("remark")+"','"+parms.getString("flag")+"','"+parms.getString("imgurl")+"'"
    					+ ",'"+parms.getString("userId")+"',now())";
            	if(DBUtils.commitOne(conn, sql)){
            		String sqlId = "select last_insert_id() id";
    				ResultSet rs = DBUtils.query(conn, sqlId);
    				if(rs.next()){
    					dataJson.put("everyId", rs.getString("id"));
    				}
    				rs.close();
            	}
            	DBUtils.endTransaction(conn);
            	response = new SuccessResponseData(dataJson);
        	}else{
        		response = new ErrorResponseData("此门店今天已经签到，请勿重复签到");
        	}
        	
        } catch (SQLException throwables) {
			
			throwables.printStackTrace();
			response = new ErrorResponseData("司机签到失败");
		} catch (Exception e) {
			e.printStackTrace();
			response = new ErrorResponseData(e.getMessage());
        } finally {
        	DBUtils.closeDBResources(conn);
		}
		return response;
	}
	
	@Override
	public ResponseData getSiji_qiandao_item(JSONObject parms) {
//		System.out.println(sql);
		try {
			
			StringBuilder sql = new StringBuilder("select * from siji_qiandao_item where flag = ? order by sort");
			JSONArray result = DBUtils.selectArr(sql.toString(),new String[]{parms.getString("flag")});
			if(result != null){
				return new SuccessResponseData(result);
			}else{
				return new ErrorResponseData("没有签到条款的信息");
			}
			
			
		} catch (SQLException throwables) {
			
			throwables.printStackTrace();
			return new ErrorResponseData("数据库操作失败！！");
		} catch (Exception e) {
			e.printStackTrace();
			return new ErrorResponseData(e.getMessage());
		}
	}

	@Override
	public ResponseData replaceSiji_qiandao_every_item(JSONObject parms) {
		try {
			DBTools.replaceBatch("everyId,shopcode,itemid,itemname,optionid,optionname,otheroptionid,otheroptionname"
					+ ",remark,imgurl,lrr,lrsj=now()", "siji_qiandao_every_item", parms.getJSONArray("dataArray"));
			
			DBTools2.update("flag", "id", "siji_qiandao_every", parms);
			
			parms.put("pingjiaType", "5");
			PingjiaUtil.insertTypePingjia(parms);
			return new SuccessResponseData();
			
		} catch (SQLException throwables) {
			
			throwables.printStackTrace();
			return new ErrorResponseData("司机签到保存失败");
		} catch (Exception e) {
			e.printStackTrace();
			return new ErrorResponseData(e.getMessage());
		}
	}

	
	
	
}

